Ext.ns('cn.hls.web.action.biz.site');
var listView = cn.hls.web.action.biz.site.listView;
var url = cfg.cxt + "/site/info.action?id=";
listView = function() {
	var store, grid, win, iframe;
	var sm = new Ext.grid.CheckboxSelectionModel({
		singleSelect : false  //单选设置为false　表示允许多选
	});
	var fields = [ "id",// 编号
	"name",//站点名称
	"contractor",//出生日期
	"contractPhone",//联系电话
	"contractIdno",//联系人身份证号
	"status",//状态  1－正常 0-暂停
	"provinceName",//所在省份
	"cityName",//所在城市
	"areaName",//所在区县
	"address",//地址
	"company"//所在单位
	
	];
	return {
		init : function() {
			  //------------------------------------------------- store
            store = this.createStore();
            //查询条件
			store.on('beforeload', function() {
				var siteType;
				if(type==''||type==undefined){
					siteType=1;
				}else{
					siteType=2;
				}
				if(queryRole){
					this.baseParams = {
						"name" : Ext.getCmp('site_name').getValue(),
						"company.name":Ext.getCmp('site_companyName').getValue(),
						"status":1,
						"type":siteType,
						'company.carryCompanyId':carryCompanyId==''?undefined:carryCompanyId
					};
				}else{
					this.baseParams = {
							"status":1,
							"type":siteType,
							'company.carryCompanyId':carryCompanyId==''?undefined:carryCompanyId
					};
				}
			});
            
			//------------------------------------------------- grid
			grid = this.createGrid();
			if(editRole){
				grid.on('rowdblclick', function(g, r, e) {
					listView.editInit();
				});
			}
			grid.on('render', function(grid) {  
			    var store = grid.getStore();  // Capture the Store.  
			    var view = grid.getView();    // Capture the GridView.  
			    grid.tip = new Ext.ToolTip({  
			        target: view.mainBody,    // The overall target element.  
			        //delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.  
			        delegate: '.x-grid3-cell',
			        trackMouse: true,         // Moving within the row should not hide the tip.  
			        renderTo: document.body,  // Render immediately so that tip.body can be  
			        anchor: 'top',                           //  referenced prior to the first show.  
			        listeners: {              // Change content dynamically depending on which element  
			                                  //  triggered the show.  
			            beforeshow: function updateTipBody(tip) {  
			            	var rowIndex = view.findRowIndex(tip.triggerElement);  
	                        var cellIndex = view.findCellIndex(tip.triggerElement);  
			                var cellIndex = view.findCellIndex(tip.triggerElement);
			                if(cellIndex>1){
				                var cell = view.getCell(rowIndex, cellIndex);  
		                        tip.body.dom.innerHTML = cell.innerHTML;  
			                }else{
			                	return false;
			                }
			            }  
			        }  
			    });  
			}); 
			
			// ------------------------------------------------- viewport
			new Ext.Viewport({ 
			      layout : 'fit',
				  items : [grid]
			});
			this.queryResItem();
		},		/**获取查询参数**/
		createStore : function() {
			return new ExtStore({
				url : '/site/list.action',
				fields : fields
			});
		},
	
		createGrid : function() {
			return new ExtGrid({
				store : store,
				title : '<div class="panelTitleCss">站点基本信息列表</div>',
				sm : sm,
				columnLines : true,
				columns : listView.createColumns(),
				tbar : listView.createQueryTbar(),
				bbar : {
					id : 'page',
					xtype : 'pageinfobar',
					pageSize : 20,
					store : store,
					pageMethod : listView.queryResItem
				}
			});
		},
		createColumns : function() {
			var cols = [
					new Ext.grid.RowNumberer(),
					sm,
					{
							sortable : true,dataIndex : "name",header:'站点名称',align:'cener',width : 80,autoWidth : true
					},
					{
						sortable : true,dataIndex : 'company',width : 90,autoWidth : true,header : '所在单位',align : 'center',
						renderer : function(value) {
							if(value!=null){
								return value.name;
							}else{
								return '';
							}
						}
					},{
						sortable : true,dataIndex : "contractor",header : '联系人',autoWidth : true,align : 'center',width : 60
					},{
						sortable : true,dataIndex : "contractPhone",header : '联系电话',autoWidth : true,align : 'center',width : 75
					},{
						sortable : true,dataIndex : "status",header : '状态',autoWidth : true,align : 'center',width : 70,
						renderer : function(value) {
							if (value != null) {
								return value==1?'正常':'暂停';
							} else {
								return '';
							}
						}
					},{
						sortable : true,dataIndex : "provinceName",header : '所在省份',autoWidth : true,align : 'center',width : 70
					},{
						sortable : true,dataIndex : "cityName",header : '所在城市',autoWidth : true,align : 'center',width : 70
					},{
						sortable : true,dataIndex : "areaName",header : '所在区县',autoWidth : true,align : 'center',width :80
					},{
						sortable : true,dataIndex : "address",header : '地址',autoWidth : true,align : 'left',width : 100
					}
			];
			return cols;
		},
		createQueryTbar : function() {
			if (queryRole) {// 查询权限
				tbarOpr.push('->');
			 
				tbarOpr.push({
					xtype : "textfield",
					width : 100,
					id : 'site_name',
					name : 'site_name',
					emptyText : '请输入站点名称',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				 
				tbarOpr.push({
					xtype : "textfield",
					width : 120,
					id : 'site_companyName',
					emptyText : '请输入单位名称',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				
				tbarOpr.push('-');
				tbarOpr.push({
					text : '查询',
					iconCls : 'mainContent',
					handler : function() {
						listView.queryResItem();
					}
				});

				tbarOpr.push({
					text : '刷新',
					iconCls : 'arrow_refreshIcon',
					handler : function() {
						store.reload();
					}
				});
			}
			return tbarOpr;
		},
		

		queryResItem : function(v) {
			var ptool = Ext.getCmp('page');
			if (!v) {
				v = ptool.pageSize;
			}
			store.load({
				params : {
					"start" : 0,
					"limit" : v
				}
			});

		},
		addInit : function() {
			this.onAddOrEditInit();
			win.show();
			win.setTitle('<div style="text-align:center;">新增站点基本信息</div>');
			Ext.getCmp('btnSave').setVisible(true);
		},

		
		editInit : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要修改的记录!');
				return;
			}
			
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条修改的记录!');
				return;
			}
			var record = sm.getSelected();
			this.onAddOrEditInit(record.data.id,false);
			win.show();
			win.setTitle('<div style="text-align:center;">修改站点基本信息</div>');
			Ext.getCmp('btnSave').setVisible(true);
		},
		show : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要查看的记录!');
				return;
			}
			
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条查看的记录!');
				return;
			}
			var record = sm.getSelected();
			this.onAddOrEditInit(record.data.id,true);
			win.show();
			win.setTitle('<div style="text-align:center;">查看站点基本信息</div>');
			Ext.getCmp('btnSave').setVisible(false);
		},
		/**编辑或新增操作**/
		onAddOrEditInit : function(id,isShow) {
			if(!win){
				win = this.createWindow(id,isShow);
			} else {
				var temp_url;
				if(id!=undefined&& id!=''&& id!=null){
					temp_url=url+id;
				}else{
					temp_url=url;
				}
				if(isShow){
					temp_url+='&show=true';
				}
				if(companyId!=''&& companyId!=undefined){
					temp_url+='&company.id='+companyId+'&type='+type;
				}
				document.getElementById("iframe").src=temp_url;
			}
		},

		subForm : function() {
			var myFrame=window.frames[0];
			var provinceName=myFrame.$("#province").find("option:selected").text();
			var cityName=myFrame.$("#city").find("option:selected").text();
			var areaName=myFrame.$("#area").find("option:selected").text();
			var streetName=myFrame.$("#street").find("option:selected").text();
			
			myFrame.$("#provinceName").val(provinceName);
			myFrame.$("#cityName").val(cityName);
			myFrame.$("#areaName").val(areaName);
			myFrame.$("#streetName").val(streetName);
			$('#subBtn', iframe.document).click();
		},

		tip : function(text) {
			Ext.Mytip.msg('提示', text);
		},

		closeWindow : function() {
			win.hide();
		},
		/**
		 * 显示窗口
		 */
		createWindow : function(id,isShow) {
			var frame_url;
			if(id!=undefined && id!=''&& id!=null){
				frame_url=url+id;
			}else{
				frame_url=url;
			}
			
			if(isShow){
				frame_url+='&show=true';
			}
			if(companyId!=''&& companyId!=undefined){
				frame_url+='&company.id='+companyId;
			}
			if(type!=''&& type!=undefined){
				frame_url+='&type='+type;
			}
			return new ExtWin({
			    width : 1024,
				height : 550,
				items : [{
					xtype : 'panel',
					html  : '<iframe id="iframe" src=' + frame_url+ ' scrolling="auto" frameborder="0" width="100%" height="100%"></iframe>'
				}],
				buttons : [{
					text : '保存',
					id:"btnSave",
					iconCls : 'acceptIcon',
					handler : function() {
						iframe = document.getElementById("iframe").contentWindow;
						listView.subForm();
					}
				},{
					text : '关闭',
					iconCls : 'deleteIcon',
					handler : function() {
						win.hide();
					}
				}]
			});
		},
		
		deleteItem : function() {
			var sm = grid.getSelectionModel();
			if (sm.getCount() == 0) {
				Ext.Mytip.msg('提示', '您尚未选择要删除的记记录！');
				return;
			}
			var ids = [];
			sm.each(function(r) {
				ids.push(r.data.id);
			});

			Ext.Msg.confirm('请确认',
					'<span style="color:red"><b>提示：</b>确定删除吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
								url : cfg.cxt + '/site/del.action',
								success : function(response) {
									var rt = Ext.decode(response.responseText);
									if (rt.success) {
										// listView.queryResItem();
										store.reload();
										Ext.Mytip.msg('提示', '删除成功！');
									} else {
										bangni.ajaxError(response);
									}
								},
								failure : bangni.ajaxError,
								params : {
									"ids" : ids.join(',')
								}
							});
						}
					});
		}
	}
}();
Ext.onReady(listView.init, listView);